<template>
  <div class="qa-container">
    <el-row :gutter="20">
      <!-- 文档内容 -->
      <el-col :span="14">
        <el-card class="document-card">
          <template #header>
            <div class="card-header">
              <span>文档内容</span>
              <span class="file-name">{{ document.fileName }}</span>
            </div>
          </template>
          <div class="document-content">
            {{ document.content }}
          </div>
        </el-card>
      </el-col>

      <!-- 问答区域 -->
      <el-col :span="10">
        <el-card class="qa-card">
          <template #header>
            <div class="card-header">
              <span>智能问答</span>
              <el-select v-model="selectedModel" placeholder="选择模型" style="margin-left: 10px;">
                <el-option label="Deepseek" value="deepseek"></el-option>
                <el-option label="通义千文" value="tongyi"></el-option>
              </el-select>
              <el-tooltip content="支持 Ctrl + Enter 快捷发送">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>

          <!-- 聊天记录 -->
          <div class="chat-container" ref="chatContainer">
            <div v-for="record in qaRecords" :key="record.id" class="chat-item">
              <div class="question">
                <el-avatar :size="32" :icon="User" />
                <div class="message">{{ record.question }}</div>
              </div>
              <div class="answer">
                <el-avatar :size="32" :icon="ChatSquare" />
                <div class="message" v-html="formatAnswer(record.answer)"></div>
              </div>
            </div>
          </div>

          <!-- 输入区域 -->
          <div class="input-area">
            <el-input
              v-model="question"
              type="textarea"
              :rows="3"
              :maxlength="500"
              show-word-limit
              placeholder="请输入您的问题..."
              @keydown.enter.ctrl.prevent="handleAsk"
              @keydown.enter.prevent="handleEnterPress"
              :disabled="loading"
            />
            <div class="button-group">
              <el-button
                type="primary"
                :loading="loading"
                @click="handleAsk"
                :disabled="!question.trim() || loading"
              >
                <el-icon><Position /></el-icon>
                发送问题
              </el-button>
              <el-button @click="question = ''" :disabled="loading">
                <el-icon><Delete /></el-icon>
                清空
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, ChatSquare, Position, Delete, QuestionFilled } from '@element-plus/icons-vue'
import axios from '../utils/axios'
import MarkdownIt from 'markdown-it'

const md = new MarkdownIt()
const route = useRoute()
const router = useRouter()
const loading = ref(false)
const document = ref({})
const qaRecords = ref([])
const question = ref('')
const chatContainer = ref(null)
const selectedModel = ref('deepseek') // 默认选择 Deepseek 模型

// 获取文档信息
const getDocument = async () => {
  try {
    const { data } = await axios.get(`/documents/${route.params.id}`)
    document.value = data
  } catch (error) {
    ElMessage.error('获取文档信息失败')
    router.push('/documents')
  }
}

// 获取问答历史
const getQAHistory = async () => {
  try {
    const { data } = await axios.get(`/qa/history/document/${route.params.id}`)
    qaRecords.value = data
    await scrollToBottom()
  } catch (error) {
    ElMessage.error('获取问答历史失败')
  }
}

// 发送问题
const handleAsk = async () => {
  if (!question.value.trim() || loading.value) {
    return
  }

  loading.value = true
  
  const newQA = {
    id: Date.now(),
    question: question.value.trim(),
    answer: '',
    timestamp: new Date().toLocaleString()
  }
  qaRecords.value.push(newQA)
  question.value = ''
  await scrollToBottom()

  try {
    const token = localStorage.getItem('token')
    const eventSource = new EventSource(
      `/api/qa/ask/stream?documentId=${route.params.id}&question=${encodeURIComponent(newQA.question)}&model=${selectedModel.value}&token=${token}`
    )

    eventSource.onmessage = (event) => {
      try {
        // 通义千问返回的是直接的文本内容
        const content = event.data
        if (content) {
          loading.value = false
          newQA.answer += content
          loading.value = true
          scrollToBottom()
        }
      } catch (e) {
        console.error('Parse message error:', e)
      }
    }

    eventSource.onerror = (error) => {
      console.error('SSE Error:', error)
      eventSource.close()
      loading.value = false
      if (!newQA.answer) {
        ElMessage.error('接收消息时发生错误')
      }
    }

    // 添加完成事件监听
    eventSource.addEventListener('complete', () => {
      console.log('Stream completed')
      eventSource.close()
      loading.value = false
    })

  } catch (error) {
    console.error('Error:', error)
    ElMessage.error('提问失败：' + (error.message || '未知错误'))
    loading.value = false
  }
}

// 处理回车按键
const handleEnterPress = (e) => {
  if (e.shiftKey || loading.value) {
    return
  }
  handleAsk()
}

// 格式化答案（支持 Markdown）
const formatAnswer = (answer) => {
  return md.render(answer)
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight
  }
}

onMounted(() => {
  getDocument()
  getQAHistory()
})
</script>

<style scoped>
.qa-container {
  max-width: 2000px;
  margin: 20px auto;
  padding: 0 30px;
  height: calc(100vh - 40px);
}

.document-card,
.qa-card {
  height: calc(100vh - 80px);
  display: flex;
  flex-direction: column;
  font-size: 18px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 25px;
}

.file-name {
  color: #666;
  font-size: 17px;
}

.document-content {
  flex: 1;
  overflow-y: auto;
  padding: 30px 40px;
  white-space: pre-wrap;
  font-size: 17px;
  line-height: 2;
  height: calc(100vh - 180px);
}

.chat-container {
  flex: 1;
  overflow-y: auto;
  padding: 30px 40px;
  height: calc(100vh - 280px);
}

.chat-item {
  margin-bottom: 30px;
}

.question,
.answer {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.message {
  background: #f4f4f5;
  padding: 20px 25px;
  border-radius: 10px;
  max-width: 85%;
  font-size: 17px;
  line-height: 2;
  color: #2c3e50;
}

.answer .message {
  background: #ecf5ff;
}

.input-area {
  padding: 25px 30px;
  border-top: 1px solid #eee;
  background-color: #fff;
}

.button-group {
  display: flex;
  gap: 15px;
  margin-top: 15px;
}

:deep(.el-input__wrapper) {
  padding: 10px 15px;
}

:deep(.el-textarea__inner) {
  font-size: 17px;
  line-height: 2;
  min-height: 150px !important;
}

:deep(.message) {
  line-height: 2;
}

:deep(.message p) {
  margin: 12px 0;
}

:deep(.message pre) {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  overflow-x: auto;
  margin: 15px 0;
  font-size: 16px;
}

:deep(.message code) {
  background: #f8f9fa;
  padding: 4px 8px;
  border-radius: 5px;
  font-size: 16px;
}

/* 优化滚动条样式 */
.document-content::-webkit-scrollbar,
.chat-container::-webkit-scrollbar {
  width: 10px;
}

.document-content::-webkit-scrollbar-thumb,
.chat-container::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 5px;
}

.document-content::-webkit-scrollbar-track,
.chat-container::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}

/* 调整头像大小 */
:deep(.el-avatar) {
  width: 40px !important;
  height: 40px !important;
  font-size: 20px !important;
}

/* 调整按钮大小 */
:deep(.el-button) {
  padding: 12px 20px;
  font-size: 16px;
}

:deep(.el-button .el-icon) {
  font-size: 18px;
}

.answer {
  white-space: pre-wrap;  /* 保持文本格式 */
  word-break: break-word; /* 防止长单词溢出 */
}
</style> 